﻿using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using Ttifa.Entity;
using Ttifa.Infrastructure;
using Ttifa.Service;
using Ttifa.WebApiBase;

namespace Ttifa.WebApi.Controllers
{
    //[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
    public class SearchController : ApiController
    {
        // GET: Search
        public ApiResult Get(string keyword)
        {
            Analyzer analyzer = new PanGuAnalyzer();
            TokenStream tokenStream = analyzer.TokenStream("", new StringReader(keyword));
            Lucene.Net.Analysis.Tokenattributes.ITermAttribute ita;
            var list = new List<string>();

            while ((tokenStream.IncrementToken()))
            {
                ita = tokenStream.GetAttribute<Lucene.Net.Analysis.Tokenattributes.ITermAttribute>();

                list.Add(ita.Term);
            }
            return new ApiResult(data: list);
        }

        public ApiResult Post()
        {
            CreateIndex();

            return new ApiResult();
        }

        private void CreateIndex()
        {
            Lucene.Net.Store.Directory dir = FSDirectory.Open(Path.Combine(HttpRuntime.AppDomainAppPath, "IndexDir"));
            IndexWriter writer = new IndexWriter(dir, new PanGuAnalyzer(),
                true, IndexWriter.MaxFieldLength.UNLIMITED);

            var service = Ninject.GetService<IArticleService>();
            var artilces = service.Get();
            foreach (var a in artilces)
            {
                var doc = new Document();
                doc.Add(new Field("Title", a.Title, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("SubTitle", a.Subtitle, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("Content", a.Content, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("CreateTime", a.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"), Field.Store.YES, Field.Index.ANALYZED));
                writer.AddDocument(doc);
            }

            writer.Optimize();
            writer.Dispose();
        }

        private void InitData()
        {
            var service = Ninject.GetService<IArticleService>();
            for (var i = 0; i < 20; i++)
            {
                var article = new Article
                {
                    Title = "标题" + i,
                    Subtitle = "小标题小小标题" + i,
                    Content = $"测试文章:这是文章这不是文章。{DateTime.Now}",
                    UpdateTime = DateTime.Now,
                    Author = "远方",
                    AuthorId = i
                };

                service.Create(article);
            }
        }
    }
}